"""
信号与槽
1、信号指触发函数
2、槽是指接受到信号时的处理函数（回调函数）
3、信号与槽需要connect链接
"""


import sys
from typing import Optional
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QApplication, QHBoxLayout, QPushButton, QWidget


class SignalSlotWidget(QWidget):
    signal_open = Signal()  # 创建一个普通的signal，不携带信息

    def __init__(self, parent: Optional[QWidget] = None) -> None:
        super().__init__(parent=parent)
        self.__init_subwidget()
        self.__init_layout()
        self.__init_connect()

    def __init_subwidget(self):
        self.open_button = QPushButton("&打开")
        self.proxy_open_button = QPushButton("&间接打开")
        self.close_button = QPushButton("&关闭")

    def __init_layout(self):
        # 水平依次添加
        hbox = QHBoxLayout()
        hbox.addWidget(self.open_button)
        hbox.addWidget(self.close_button)
        hbox.addWidget(self.proxy_open_button)

        self.setLayout(hbox)

    def __init_connect(self):
        self.open_button.pressed.connect(self.__slot_pressed)
        self.open_button.released.connect(self.__slot_released)
        # clicked 必须pressed和released都在范围内
        self.open_button.clicked.connect(self.__slot_clicked)
        self.close_button.clicked.connect(self.close)           # 关闭button会触发关闭
        self.close_button.released.connect(self.__slot_released)
        self.proxy_open_button.clicked.connect(self.__slot_clicked)
        self.proxy_open_button.clicked.connect(
            self.__slot_emit_proxy)  # connect到两个函数会顺序调用
        self.signal_open.connect(self.open_button.click)        # 将信号和回调函数链接

    def __slot_clicked(self, state: bool): print(self.sender().text()+"被点击")
    def __slot_pressed(self): print(self.sender().text()+"鼠标已点击")
    def __slot_released(self): print(self.sender().text()+"鼠标在同一组件释放")
    def __slot_emit_proxy(self): self.signal_open.emit()


if __name__ == "__main__":
    # 主流程控制，一个程序只能有一个QApplication，sys可以用于命令行导入
    app = QApplication(sys.argv)
    window = SignalSlotWidget()
    window.show()
    sys.exit(app.exec())               # 控制程序安全退出
